package com.ztstkj.lzservices.networks

import android.content.Context
import android.net.ConnectivityManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Callable
import java.util.concurrent.Executors


class NetworkUtils {
    companion object {
        var onLine:Boolean=true
        //判断网络状态，有网络返回true
        fun isConnected(context: Context): Boolean {
            val isNetwork = (isNetworkConnected(context) || isWifiConnected(context))
            if(!isNetwork) return false
            val isOnline = isOnlineByExecutor()
            //if(!isOnline) SpeakUtil.speech(context,"当前没有网络")
            return isOnline
            //val isOnline = coroutineScope.async {isOnline()}
        }

        //判断手机是否有网络连接
        private fun isNetworkConnected(context: Context?): Boolean {
            if (context != null) {
                val mConnectivityManager =
                    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mNetworkInfo = mConnectivityManager.activeNetworkInfo
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable
                }
            }
            return false
        }

        //判断wifi网络是否可用
        private fun isWifiConnected(context: Context?): Boolean {
            if (context != null) {
                val mConnectivityManager =
                    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val mNetworkInfo =
                    mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isAvailable
                }
            }
            return false
        }

        private fun isOnlineByExecutor(): Boolean {
            val executor = Executors.newSingleThreadExecutor()
            val future = executor.submit(Callable {
                try {
                    val url = URL("https://www.baidu.com") // 使用baidu的公共DNS作为测试地址
                    val connection = url.openConnection() as HttpURLConnection
                    connection.setRequestMethod("HEAD")
                    connection.setRequestProperty("User-Agent", "Android")
                    connection.setRequestProperty("Connection", "close")
                    connection.connectTimeout = 500 // 设置连接超时为5秒
                    connection.connect()
                    val responseCode = connection.responseCode
                    connection.disconnect()
                    return@Callable responseCode == HttpURLConnection.HTTP_OK // 200 OK 表示连接成功
                } catch (e: IOException) {
                    return@Callable false
                }
            })
            val result = future.get()
            executor.shutdown()
            return result

        }
        // 想用协程不会用！！！
        private suspend fun isOnline(): Boolean {
            return withContext(context = Dispatchers.IO) {
                try {
                    val url = URL("https://www.baidu.com") // 使用baidu的公共DNS作为测试地址
                    val connection = url.openConnection() as HttpURLConnection
                    connection.setRequestMethod("HEAD")
                    connection.setRequestProperty("User-Agent", "Android")
                    connection.setRequestProperty("Connection", "close")
                    connection.connectTimeout = 700 // 设置连接超时为5秒
                    connection.connect()
                    val responseCode = connection.responseCode
                    connection.disconnect()
                    responseCode == HttpURLConnection.HTTP_OK // 200 OK 表示连接成功
                } catch (e: IOException) {
                    false // 出现异常，表示网络不可用或连接失败
                }
            }

        }
    }
}